import { Message } from 'element-ui';

import { submitEncodeMessage} from '@/utils/common';
import { loginFunApi as login, outLoginFun as logout } from '@/api/login';
import { LOCAL_KEY} from '@/constant/dict';
import router from '@/router';
import i18n from '@/lang';
import { commit } from 'lodash-es';

const state = {
    token:localStorage.getItem("token") || "",
    // 用户名
    username: '',
    // 密码
    password: '',
    // 是否记住密码
    rememberPassword: false,
    // 用户分组
    group: ''
};

const auth = {
    state,
    actions: {
        async LOGIN({ commit, dispatch }, userInfo) {
            try {
                // 清除流量限制标志，用于登录之后重新提醒
                if (localStorage.getItem(LOCAL_KEY.IS_TRAFFIC_LIMIT)) {
                    localStorage.removeItem(LOCAL_KEY.IS_TRAFFIC_LIMIT);
                }

                const {password, rememberPassword} = userInfo;
                // 密码为空
                if (!password) {
                    Message.error(i18n.t('errorTips.loginPasswordEmpty'));
                    return;
                }
               
                const res = await login(submitEncodeMessage(password));
                
                console.log('登录响应:', res); // 输出登录响应信息

                const { token, remainTimes, timeLeft } = res;
                commit('SET_TOKEN', token);

                const time = Math.ceil(timeLeft / 60);

                // 用户名或密码错误提示
                let loginErrTips = i18n.t('login.reason_text21', { XXX: remainTimes });
                let loginErrTipsByCount = i18n.t('login.reason_text31', { XXX: time });
                console.log(loginErrTips,loginErrTipsByCount);

                // 记住密码时储存本地的数据
                const localStorageData = {
                    password,
                    rememberPassword
                };

                console.log('登录成功，开始处理后续操作'); // 输出登录成功状态
                            
                try {
                    // get 读取配置类型
                    await dispatch('config/LOAD_CONFIG');
                    commit('SET_REMEMBER_PASSWORD', rememberPassword);
                    console.log('登录成功，开始设置登录标志');
                    
                    // 跳转页面
                    let targetPage = '/home';
                    console.log('准备跳转到页面:', targetPage);
                    // window.location.href = '/home';
                    router.push(targetPage);
                } catch (error) {
                    console.error('登录成功后处理出错:', error);
                    Message.error(i18n.t('errorTips.loginSuccess_processError'));
                }

            } catch (error) {
                console.error('登录过程出错:', error);
                Message.error(i18n.t('errorTips.loginFail'));
            }
        },

        async LOGOUT() {
            try {
                commit('SET_TOKEN', '');
                
                await logout();
                
            }catch (error) {
                console.log('登出过程出错:', error);
            }

            // 清空所有localStorage缓存
            localStorage.clear();
            router.push('/login');
            //window.location.href = '/login_new.html';
        }
    },

    mutations: {
        // 设置是否记住密码
        SET_REMEMBER_PASSWORD: (state, value) => {
            state.rememberPassword = value;
        },

        // 设置用户分组
        SET_GROUP: (state, value) => {
            state.group = value;
        },

        // 设置token
        SET_TOKEN: (state, value) => {
            console.log('SET_TOKEN:', value);
            state.token = value;
            localStorage.setItem(LOCAL_KEY.IS_AUTH_TOKEN, value);
        },
    }
};

export default auth;
